package org.itkk.udf.service.a.demo.service;

import lombok.extern.slf4j.Slf4j;
import org.itkk.udf.service.a.demo.UdfServiceADemoConfig;
import org.itkk.udf.service.a.demo.domain.TestMsg;
import org.itkk.udf.service.a.demo.repository.ITestMsgRespository;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

@Service
@Slf4j
public class MessageService {
    /**
     * SCHEDULED_FIXEDRATE
     */
    private static final long SCHEDULED_FIXEDRATE = 1000;

    /**
     * amqpTemplate
     */
    @Autowired
    private AmqpTemplate amqpTemplate;

    /**
     * testMsgRespository
     */
    @Autowired
    private ITestMsgRespository testMsgRespository;

    /**
     * consume11
     *
     * @param testMsg testMsg
     */
    @RabbitListener(queues = UdfServiceADemoConfig.QUEUE_ADEMO_TEST1_CONSUME1)
    public void consume1(TestMsg testMsg) {
        if (testMsgRespository.count(testMsg.getBusinessKey()) > 0) {
            int row = testMsgRespository.update(testMsg);
            log.info("update row = {}", row);
        } else {
            try {
                int row = testMsgRespository.insert(testMsg);
                log.info("insert row = {}", row);
            } catch (Exception e) {
                int row = testMsgRespository.update(testMsg);
                log.info("update row = {}", row);
            }
        }
        try {
            final long time = 5L;
            Thread.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * send
     */
    @Scheduled(fixedRate = SCHEDULED_FIXEDRATE)
    public void send1() {
        this.send();
    }

    /**
     * send
     */
    @Scheduled(fixedRate = SCHEDULED_FIXEDRATE)
    public void send2() {
        this.send();
    }

    /**
     * send
     */
    @Scheduled(fixedRate = SCHEDULED_FIXEDRATE)
    public void send3() {
        this.send();
    }


    /**
     * send
     */
    @Scheduled(fixedRate = SCHEDULED_FIXEDRATE)
    public void send4() {
        this.send();
    }

    /**
     * send
     */
    private void send() {
        final int numA = 1000;
        int a = (int) (Math.random() * numA);
        long b = (long) (Math.random() * numA);
        TestMsg testMsg = new TestMsg();
        testMsg.setBusinessKey(Integer.toString(a));
        testMsg.setVersion(b);
        testMsg.setData(UUID.randomUUID().toString());
        testMsg.setLastUpdatedDate(new Date());
        amqpTemplate.convertAndSend(UdfServiceADemoConfig.EXCHANGE_ADEMO_TEST1, UdfServiceADemoConfig.ROUTINGKEY_ADEMO_TEST1_TESTMSG, testMsg);
    }
}
